package org.dei.perla.rockfall.gui.queryforge;

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Map;

import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;

import org.dei.perla.sys.device.fpc.dspic.datastructures.DSPicDefines;
import org.dei.perla.sys.device.fpc.dspic.datastructures.MRP;
import org.dei.perla.utils.dataconverter.DataConverter;


public class QueryForgeMain extends JFrame implements ActionListener, ClipboardOwner {

	private static final String IMPORT_PARAMS_FILE = "ifp";
	private static final String GENERATE_QUERY = "gen";
	private static final String IMPORT_FILTER_FILE_X = "ifx";
	private static final String IMPORT_FILTER_FILE_Y = "ify";
	private static final String IMPORT_FILTER_FILE_Z = "ifz";
	private static final String EXIT = "exit";
	private static final String SAVE_SESSION = "save";
	private static final String DEFAULT_SESSION_NAME = ".qfsession";
	
	/**
	 * @param args
	 */
	private JFileChooser fileChooser;
	private JDialog dialog;
	private QueryForgeRootPanel rootPanel;
	private DSPicParameters parameters;
	private JMenuBar menuBar;
	private String defaultFilePath;
	
	private void privateInit1(){
		Map<String, String> map = System.getenv();
		this.defaultFilePath = new String(map.get("HOME"));
		this.fileChooser = new JFileChooser();
	}
	
	private void privateInit2(){
		this.rootPanel = new QueryForgeRootPanel(parameters);
		this.setupMenu();
		this.add(rootPanel);
		this.pack();
		this.rootPanel.updateConfiguration();		
		this.setVisible(true);
	}
	
	public QueryForgeMain(DSPicParameters parameters2) {
		super();
		this.privateInit1();
		this.parameters = parameters2;
		privateInit2();
	}

	private void setupMenu() {
		this.menuBar = new JMenuBar();
		JMenu menu = new JMenu("File");
		
		JMenuItem importItem = new JMenuItem("Importa file parametri");
		importItem.setActionCommand(QueryForgeMain.IMPORT_PARAMS_FILE);
		importItem.addActionListener(this);
		
		JMenuItem generateItem = new JMenuItem("Genera query");
		generateItem.setActionCommand(QueryForgeMain.GENERATE_QUERY);
		generateItem.addActionListener(this);
		
		JMenuItem importFilterX = new JMenuItem("Importa file filtri asse X");
		importFilterX.setActionCommand(QueryForgeMain.IMPORT_FILTER_FILE_X);
		importFilterX.addActionListener(this);
		
		JMenuItem importFilterY = new JMenuItem("Importa file filtri asse Y");
		importFilterY.setActionCommand(QueryForgeMain.IMPORT_FILTER_FILE_Y);
		importFilterY.addActionListener(this);
		
		JMenuItem importFilterZ = new JMenuItem("Importa file filtri asse Z");
		importFilterZ.setActionCommand(QueryForgeMain.IMPORT_FILTER_FILE_Z);
		importFilterZ.addActionListener(this);
		
		JMenuItem saveItem = new JMenuItem("Salva sessione");
		saveItem.setActionCommand(QueryForgeMain.SAVE_SESSION);
		saveItem.addActionListener(this);
		
		JMenuItem quit = new JMenuItem("Esci");
		quit.setActionCommand(QueryForgeMain.EXIT);
		quit.addActionListener(this);

		
		menu.add(generateItem);
		menu.add(importFilterX);
		menu.add(importFilterY);
		menu.add(importFilterZ);
		menu.add(importItem);
		menu.add(saveItem);
		menu.add(quit);
		this.menuBar.add(menu);
		this.setJMenuBar(menuBar);	
	}

	public static void main2(String[] args){
		try {
			FileOutputStream output = new FileOutputStream(new File(args[0]));
			MRP mrp = new MRP();
			mrp.setAcquisitionType(0);
			mrp.setCommand(0xff);
			mrp.setCrackBias(0xab);
			mrp.setGx(0x1);
			mrp.setGy(0x2);
			mrp.setGz(0x4);
			mrp.setLtaInterSample(0xf0);
			mrp.setMx(0x8);
			mrp.setMy(0x10);
			mrp.setMz(0x20);
			mrp.setRs1(0x2107);
			mrp.setRs2(0x3751);
			mrp.setRs3(0x0000);
			mrp.setRs4(0x1786);
			
			int vect[] = new int[DSPicDefines.MRP_TAPS_SIZE];
			
			for(int i = 0; i < vect.length ; i++){
				vect[i] = i;
			}
			
			mrp.setTapsx(vect);
			mrp.setTapsy(vect);
			mrp.setTapsz(vect);
			
			Byte serialized[] = DataConverter.toByteArray(mrp);
			for(Byte b : serialized){
				output.write(b);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
	public static void main(String[] args) throws ClassNotFoundException {
		Map<String, String> map = System.getenv();
		final String pwd = new String(map.get("HOME"));
		System.out.println(pwd + "/" + DEFAULT_SESSION_NAME);
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
				@Override
				public void run() {
					DSPicParameters dspicParams;
					MRP parameters = SessionManager.restoreSession(pwd + "/" + DEFAULT_SESSION_NAME);
					if(parameters == null){
						System.out.println("impossibile leggere il file");
						dspicParams = new DSPicParameters();
					}
					else{					
						dspicParams = new DSPicParameters(parameters);
						System.out.println(dspicParams.toString());						
					}
					QueryForgeMain windows = new QueryForgeMain(dspicParams);
				}
			});
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		System.out.println(e.getActionCommand());
		String command = e.getActionCommand();
		if(command.equals(EXIT)){
			System.exit(0);
		}
		if(command.equals(GENERATE_QUERY)){
			System.out.println(parameters.toString());
			try {
				rootPanel.readConfiguration();
				System.out.println(parameters.toString());
				StringSelection stringSelection = new StringSelection(parameters.toString());
			    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
			    clipboard.setContents( stringSelection, this );
				JOptionPane.showMessageDialog(this, "La query e' stata messa sulla clipbord");
			} catch (IllegaParamValueException e1) {
				// TODO Auto-generated catch block
				JOptionPane.showMessageDialog(this, e1.getMessage());
			}
		}
		if(command.equals(SAVE_SESSION)){
			System.out.println("sav");
			try {
				this.rootPanel.readConfiguration();
				if(SessionManager.saveSession(this.parameters.getParameter(), defaultFilePath + "/" + DEFAULT_SESSION_NAME) == false)
					System.out.println("Errore scrivendo il file");
			} catch (IllegaParamValueException e1) {
				// TODO Auto-generated catch block
				JOptionPane.showMessageDialog(this, e1.getMessage());
				e1.printStackTrace();
			}
			/*FileOutputStream f;
			ObjectOutputStream f2;
			f2.wr*/
		}
		if(command.endsWith(IMPORT_FILTER_FILE_X)){
			fileChooser.setFileFilter(new FileFilter() {
				
				@Override
				public String getDescription() {
					return "File dei filtri *.flt";
				}
				
				@Override
				public boolean accept(File f) {
					if(f.getName().endsWith("flt"))
						return true;
					return false;
				}
			});
			
			if(fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION){
				File file = fileChooser.getSelectedFile();
				try {
					int taps[] = FilterFileParser.parse(new BufferedReader(new FileReader(file)));
					this.parameters.setTapsx(taps);
					rootPanel.updateConfiguration();
					JOptionPane.showMessageDialog(this, "Filtro X importato correttamente");
				} catch (FileNotFoundException e1) {
					// TODO Auto-generated catch block
					JOptionPane.showMessageDialog(this, e1.getMessage());
				} catch (FilterFileParserException e1) {
					// TODO Auto-generated catch block
					JOptionPane.showMessageDialog(this, e1.getMessage());				
				}
			}
		}
		
		if(command.endsWith(IMPORT_FILTER_FILE_Y)){
			fileChooser.setFileFilter(new FileFilter() {
				
				@Override
				public String getDescription() {
					return "File dei filtri *.flt";
				}
				
				@Override
				public boolean accept(File f) {
					if(f.getName().endsWith("flt"))
						return true;
					return false;
				}
			});
			
			if(fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION){
				File file = fileChooser.getSelectedFile();
				try {
					int taps[] = FilterFileParser.parse(new BufferedReader(new FileReader(file)));
					this.parameters.setTapsy(taps);
					rootPanel.updateConfiguration();
					JOptionPane.showMessageDialog(this, "Filtro Y importato correttamente");
				} catch (FileNotFoundException e1) {
					// TODO Auto-generated catch block
					JOptionPane.showMessageDialog(this, e1.getMessage());
				} catch (FilterFileParserException e1) {
					// TODO Auto-generated catch block
					JOptionPane.showMessageDialog(this, e1.getMessage());				
				}
			}
		}
		
		if(command.endsWith(IMPORT_FILTER_FILE_Z)){
			fileChooser.setFileFilter(new FileFilter() {
				
				@Override
				public String getDescription() {
					return "File dei filtri *.flt";
				}
				
				@Override
				public boolean accept(File f) {
					if(f.getName().endsWith("flt"))
						return true;
					return false;
				}
			});
			
			if(fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION){
				File file = fileChooser.getSelectedFile();
				try {
					int taps[] = FilterFileParser.parse(new BufferedReader(new FileReader(file)));
					this.parameters.setTapsz(taps);
					rootPanel.updateConfiguration();
					JOptionPane.showMessageDialog(this, "Filtro Z importato correttamente");
				} catch (FileNotFoundException e1) {
					JOptionPane.showMessageDialog(this, e1.getMessage());
				} catch (FilterFileParserException e1) {
					JOptionPane.showMessageDialog(this, e1.getMessage());				
				}
			}
		}
		
		if(command.endsWith(IMPORT_PARAMS_FILE)){
			
			if(fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION){
				File file = fileChooser.getSelectedFile();
				try {
					ParserParamFile.parse(file, this.parameters.getParameter());
					rootPanel.updateConfiguration();
					JOptionPane.showMessageDialog(this, "Parametri importati correttamente");
				} catch (FilterFileParserException e1) {
					JOptionPane.showMessageDialog(this, e1.getMessage());
				} catch (IOException e1) {
					JOptionPane.showMessageDialog(this, e1.getMessage());
				}
			}
		}
		
	}

	@Override
	public void lostOwnership(Clipboard clipboard, Transferable contents) {
		// TODO Auto-generated method stub
		
	}

}
